<template>
	<view class="box">
		<!-- 选择会员 -->
		<view class="selectMember">
			<view class="member">
				<view @click="selected==1?false:dialog = true">{{userName || '会员：'}}</view>
				<view style="position: relative;">{{fillFormDate || '日期：'}}
					<picker mode="date" :start="start" :end="end"  @change="bindDateChange" :disabled="selected==1" style="position: absolute;left:0;top: 0;width: 100%;height: 100%;">
						<view class="date">{{fillFormDate}}</view>
					</picker> 
				</view>
			</view>
			<view class="save" @click="save(1)" v-if="!selected">保存</view>
			<view class="toSend" @click="save(3)">生成评估</view>
		</view>
		
		<view class="content">
			<view class="question" v-for="(item,index) in questionnaire" :key="index">
				<view class="title">
					<text>{{index <= 8 ? '0'+(index+1) : index+1}}</text>
					<view>{{item.name}}</view>
				</view>
				<view class="entry" v-if="item.adTopicsRepliesEntityList.length <= 0">
					<input type="number"  @blur="regular($event,item,name='oneDecimal')" placeholder="空腹血糖(GLU)" v-model="item.envalue" v-if="item.name.indexOf('空腹血糖') > -1">
					<input type="number"  @blur="regular($event,item,name='oneDecimal')" placeholder="餐后2小时血葡萄糖(2HPG)" v-model="item.envalue" v-else-if="item.name.indexOf('葡萄糖') > -1">
					<input type="number"  @blur="regular($event,item,name='oneDecimal')" placeholder="体重指数（BMI）" v-model="item.envalue" v-else-if="item.name.indexOf('体重指数') > -1">
					<input type="number"  @blur="regular($event,item,name='oneDecimal')" placeholder="高密度脂蛋白（DHL）" v-model="item.envalue" v-else-if="item.name.indexOf('高密度脂蛋白') > -1">
					<input type="number"  @blur="regular($event,item,name='twoDecimal')" placeholder="甘油三酯（TG）" v-model="item.envalue" v-else-if="item.name.indexOf('甘油三酯') > -1">
					<input type="number"  @blur="regular($event,item,name='integer')" placeholder="0-7" v-model="item.envalue" v-else-if="item.name.indexOf('运动') > -1">
					<input type="number"  @blur="regular($event,item,name='integer')" placeholder="数值" v-model="item.envalue" v-else>
				</view>
				<view v-else>
					<view class="option" v-for="(aitem,aindex) in item.adTopicsRepliesEntityList" :key="aindex">
						<view  @click="answer(item,aitem)">
							<text>{{aitem.elections}}、{{aitem.value}}</text> 
							<image src="@/static/img/select@2x.png" v-if="aitem.checked == false"></image>
							<image src="@/static/img/selected@2x.png" v-else></image>
						</view>
					</view>
					<input type="text" class="s-input" placeholder="腰围" v-if="item.name.indexOf('腰围') > -1" v-model="item.envalue">
				</view>
			</view>
		</view>
		<!-- 会员弹框 -->
		<member :dialog.sync="dialog"  @hidedialog="hidedialog" @chooseUser="chooseUser"></member>
		<reportImgType ref="reportImgType" :info="info"></reportImgType>
	</view>
</template>

<script>
	import { getUrlParam,regular } from '@/static/js/filter.js';
	import reportImgType from './reportImgType.vue'
	import member  from '@/components/selectMember/selectMember.vue';
	export default {
		components:{member,reportImgType},
		data () {
			const currentDate = this.getDate({
				format: true
			})
			return {
				userName:'',
				start: '',
				end: currentDate,
				fillFormDate:'',
				showModal1: false, //选择日期弹框组件
				dialog: false,
				selected:'',
				systolicPressure:'', //收缩压
				diastolicPressure:'', //舒张压
				questionnaire:[],
				info:{},
				selected: 0
			}
		},
		onLoad(options){
			this.findByTopicsTypeAxios().then(()=>{
				if(options.id){
					if(options.selected){
						this.selected = options.selected
					}
					this.editId = options.id
					this.$api.appDiseaseDangeDetail(options.id).then((res)=>{
						this.fillFormDate = res.data.result.fillFormDate
						this.userId = res.data.result.userId
						this.userName = res.data.result.userName
						this.tid = res.data.result.tid
						this.questionnaire.map((a)=>{
							res.data.result.userTopicsEntities.map((b)=>{
								if(a.id == b.titleId){
									a.nid = b.id
									if(b.titleId == 220){
										// 收缩压
										this.systolicPressure = b.userValue.split('/')[0]
										this.diastolicPressure = b.userValue.split('/')[1]
									}else if(b.userOption){
										// 选项
										a.adTopicsRepliesEntityList.map((c)=>{
											if(c.elections == b.userOption){
												c.nid = b.id
												c.checked = true
											}
										})
									}else{
										a.envalue = b.userValue
									}
								}
							})
						})
					})
				}
			})
		},
		methods:{
			regular,
			//选答案
			answer(aitem,bitem) {
				if(this.selected == 1){
					return;
				}
				const answerArr = aitem.adTopicsRepliesEntityList.map((a) => {
					a.checked = false;
					return a
				})
				bitem.checked = true;
			},
			//关闭弹出框
			hidedialog(){
				this.dialog = false
			},
			//选择会员
			chooseUser(e){
				this.userId = e.userId;
				this.userName = e.userName;
			},
			// 日期
			bindDateChange(e) { 
				this.fillFormDate = e.target.value;
			},
			// 获取当前时间
			getDate(type) {
			   const date = new Date();
			   let year = date.getFullYear();
			   let month = date.getMonth() + 1;
			   let day = date.getDate();
			  
			   if (type === 'start') {
				year = year - 60;
			   } else if (type === 'end') {
				year = year + 2;
			   }
			   month = month > 9 ? month : '0' + month;;
			   day = day > 9 ? day : '0' + day;
			   return `${year}-${month}-${day}`;
			},
			// 获取题目
			findByTopicsTypeAxios(){
				return new Promise((success,error)=>{
					this.$api.findByTopicsType('ids=45').then((res)=>{
						if(res){
							const data = res.data.result[45].adTopicsRepliesEntityList.map((b)=>{
								b.envalue = ''
								b.adTopicsRepliesEntityList.map((c)=>{c.checked = false;return b})
								return b
							})
							this.questionnaire = data
							success(res.data.result)
						}else{
							error('')
						}
					})
				})
			},
			save(e){
				const _this = this;
				if(!this.userId){
					uni.showToast({
						title:'请选择会员',
						icon:'none'
					})
					return
				}
				if(!this.fillFormDate){
					uni.showToast({
						title:'请选择填写时间',
						icon:'none'
					})
					return
				}
				var emptyArr = []
				var HasArr = []
				this.questionnaire.map((a)=>{
					a.envalue = a.envalue+''
					if(a.adTopicsRepliesEntityList.length > 0){
						if(JSON.stringify(a.adTopicsRepliesEntityList).indexOf('true') == -1){
							emptyArr.push(a)
						}else{
							HasArr.push(a)
						}
					}else{
						if(a.envalue == ''){
							emptyArr.push(a)
						}else{
							HasArr.push(a)
						}
					}
				})
				if(emptyArr.length > 0){
					if(emptyArr[0].adTopicsRepliesEntityList.length > 0){
						uni.showToast({
							title:'请选择'+emptyArr[0].name,
							icon:'none'
						})
						return
					}else{
						uni.showToast({
							title:'请输入'+emptyArr[0].name,
							icon:'none'
						})
						return
					}
				}
				const appUserTopicsEntities = []
				HasArr.map((a)=>{
					if(a.adTopicsRepliesEntityList.length > 0){
						const checked = a.adTopicsRepliesEntityList.filter((c)=>{return c.checked})
						appUserTopicsEntities.push({
							titleId:a.id,
							id:checked && checked[0] && checked[0].nid || '', //编辑时需要
							userOption:checked[0].elections,
							userValue: checked[0].value,
							type:a.type
						})
					}else{
						appUserTopicsEntities.push({
							titleId:a.id,
							id:a.nid, //编辑时需要
							userOption:'',
							userValue: a.envalue,
							type:a.type
						})
					}
				})
				const data = {
					appUserTopicsEntities:appUserTopicsEntities,
					status: e,
					type: 9,
					userHealthId:JSON.parse(localStorage.userInfo).id,
					userHealthName:JSON.parse(localStorage.userInfo).realName,
					userId:this.userId,
					title: 42,
					source: 3,
					userName: this.userName,
					fillFormDate:this.fillFormDate
				}
				uni.showLoading({title:'加载中'})
				if(e == 1){
					if(_this.editId){
						data.id = Number(_this.editId)
						data.appUserTopicsTitleEntity = {
							healthId:JSON.parse(localStorage.userInfo).id,
							userId:_this.userId
						}
						data.tid = _this.tid
						_this.$api.appDiseaseDangeUpdate(data).then((res)=>{
							uni.hideLoading()
							uni.showToast({
								title: '保存成功',
								icon: 'none'
							})
							uni.navigateTo({
								url:'/pages/futureDiseases/navigation?current=1'
							})
						})
					}else{
						_this.$api.appDiseaseDangeAdd(data).then((res)=>{
							if (res.data.returnCode == 200) {
								uni.hideLoading()
								uni.showToast({
									title: '保存成功',
									icon: 'none'
								})
								uni.navigateTo({
									url:'/pages/futureDiseases/navigation?current=1'
								})
							}
						})
					}
				}else{
					if(_this.editId){
						data.id = Number(_this.editId)
						data.appUserTopicsTitleEntity = {
							healthId:JSON.parse(localStorage.userInfo).id,
							userId:_this.userId
						}
						data.tid = _this.tid
						_this.$api.appDiseaseDangeReport(data).then((res)=>{
							if (res.data.returnCode == 200) {
								_this.info = res.data.result
								// uni.hideLoading()
								setTimeout(()=>{
									_this.$refs.reportImgType.toImg().then((base64)=>{
										var arr = base64.split(',')
										var mime = arr[0].match(/:(.*?);/)[1]
										var bstr = atob(arr[1]) 
										var nn = bstr.length 
										var u8arr = new Uint8Array(nn);
										while(nn--){
											u8arr[nn] = bstr.charCodeAt(nn);
										}
										var obj = new Blob([u8arr], {type:mime});
										var formData = new FormData()
										formData.append('fileOne ', obj)  
										_this.$api.appSicknessDangeUpdateUploadWord(data.id,formData).then((ares) => {
											uni.hideLoading()
											if(ares.data.returnCode == 200){
												window.location.href = 'http://health.jlm12580.com/web/viewer.html?file='+ares.data.result.url
											}
										})
									})
								},1000)
							}
						})
					}else{
						_this.$api.appDiseaseDangeAdd(data).then((res)=>{
							if (res.data.returnCode == 200) {
								data.id = Number(res.data.result.id)
								data.appUserTopicsTitleEntity = {
									healthId:JSON.parse(localStorage.userInfo).id,
									userId:_this.userId
								}
								_this.$api.appDiseaseDangeReport(data).then((res2)=>{
									if (res2.data.returnCode == 200) {
										// uni.hideLoading()
										_this.info = res2.data.result
										setTimeout(()=>{
											_this.$refs.reportImgType.toImg().then((base64)=>{
												var arr = base64.split(',')
												var mime = arr[0].match(/:(.*?);/)[1]
												var bstr = atob(arr[1]) 
												var nn = bstr.length 
												var u8arr = new Uint8Array(nn);
												while(nn--){
													u8arr[nn] = bstr.charCodeAt(nn);
												}
												var obj = new Blob([u8arr], {type:mime});
												var formData = new FormData()
												formData.append('fileOne ', obj)  
												_this.$api.appSicknessDangeUpdateUploadWord(data.id,formData).then((ares) => {
													uni.hideLoading()
													if(ares.data.returnCode == 200){
														window.location.href = 'http://health.jlm12580.com/web/viewer.html?file='+ares.data.result.url
													}
												})
											})
										},1000)
									}
								})
							}
						})
					}
				}
			}
		}
	}
</script>

<style lang="scss" scoped>
	@import '@/static/css/quickly/healthStatus/common.scss';
	.entry {
		display: flex;
		margin:30upx 0 0 58upx;
		input {
			font-size: 30upx;
			color: #333333;
			width: 100%;
		}
		.systolicPressure {
			width: 148upx;
		}
		.diastolicPressure {
			margin-left: 60upx;
			flex: 1;
		}
	}
	.s-input{
		border: 2upx solid #E3E3E3;
		height: 60upx;
		background: #FBFBFB;
		border-radius: 8upx;
		margin-top: 18upx;
		padding-left: 10upx;
	}
</style>
